package com.lisa.auto.controller.excel;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSONArray;
import com.google.common.base.Strings;
import com.lisa.auto.entity.ceramics.ResultPo;
import com.lisa.auto.entity.excel.OrderTmplPo;
import com.lisa.auto.service.excel.CeramicsImportService;
import com.lisa.auto.service.excel.SevenElevenImportService;
import com.lisa.auto.util.Cache;
import com.lisa.auto.util.DateUtil;
import com.lisa.auto.util.ExcelUtils;
import com.lisa.auto.util.JxlExcelUtils;
import com.lisa.date.DateTime;
import com.lisa.redis.JedisClusterUtil;
import com.lisa.util.RestfulResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
 * @author huangzhigang 2019/12/2
 */
@RestController
@Api(description = "导入Excel")
@RequestMapping(value = "/excel", produces = MediaType.APPLICATION_JSON_VALUE)
public class ExcelImportController {

    @Autowired
    private SevenElevenImportService sevenElevenImportService;
    @Autowired
    private CeramicsImportService ceramicsImportService;



    private Cache<SXSSFWorkbook> RESOURCES = new Cache<>();

    /**
     * 导入711运单
     *
     * @return RestfulResponse
     */
    @ApiOperation(value = "导入711订单信息", notes = "导入711订单信息")
    @RequestMapping(value = "/importOrderExcel", method = RequestMethod.POST)
    public void importOrderExcel(@RequestParam("file") MultipartFile file, HttpServletResponse response) {
        sevenElevenImportService.importExcel(file, response);
    }

    @ApiOperation(value = "转换装车单", notes = "转换装车单")
    @RequestMapping(value = "/transVehicleExcel", method = RequestMethod.POST)
    public void transVehicleExcel(HttpServletResponse response, MultipartHttpServletRequest request) {
        List<MultipartFile> files = request.getFiles("file");
        for (MultipartFile file : files) {
            System.out.println(file.getOriginalFilename());
        }
        MultipartFile orderFile = files.get(0);
        MultipartFile vehicleFile = files.get(1);
        sevenElevenImportService.transVehicleExcel(orderFile, vehicleFile, response);
    }

    @RequestMapping("/index")
    public ModelAndView index() {
        ModelAndView model = new ModelAndView();
        model.setViewName("/excel/import");
        return model;
    }

    @RequestMapping("/load")
    public ModelAndView loadSingle() {
        ModelAndView model = new ModelAndView();
        model.setViewName("/excel/load_single");
        return model;
    }


    @RequestMapping("/importVehicle")
    public ModelAndView importVehicle() {
        ModelAndView model = new ModelAndView();
        model.setViewName("/excel/importVehicle");
        return model;
    }

    @ApiOperation(value = "导出资源文件", notes = "导出资源文件", httpMethod = "GET")
    @GetMapping("/exportResource")
    public RestfulResponse<String> exportResouce(@RequestParam String key, HttpServletResponse response) throws IOException {
        if (Strings.isNullOrEmpty(key)) {
            return new RestfulResponse<>(-1, "文件key接收异常", null);
        }
        RestfulResponse<String> restful = new RestfulResponse<>(0, "导出成功", null);
        //获取缓冲区数据资源
        SXSSFWorkbook excel = RESOURCES.get(key);
        if (Objects.isNull(excel)) {
            //未获取到资源抛出提示
            restful = new RestfulResponse<>(-1, "资源文件不存在", null);
        } else {
            String fileName = "装车单" + new DateTime().toString("yyyyMMddHHmm");
            fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
            RESOURCES.remove(key);
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xls");
            OutputStream ouputStream = response.getOutputStream();
            excel.write(ouputStream);
            ouputStream.flush();
            ouputStream.close();
        }
        return restful;
    }


    /**
     * 导入陶瓷原始单信息
     * @param response
     * @param request
     */
    @ApiOperation(value = "导入陶瓷原始单信息", notes = "导入陶瓷原始单信息")
    @RequestMapping(value = "/importCeramicsOrderExcel", method = RequestMethod.POST)
    @ResponseBody
    public List<ResultPo> importCeramicsOrderExcel(HttpServletResponse response, MultipartHttpServletRequest request) {
        List<MultipartFile> fileList = request.getFiles("file");
        return ceramicsImportService.importExcel(fileList, response);
    }

    @RequestMapping("/transform")
    public ModelAndView toCeramicsTransform() {
        ModelAndView model = new ModelAndView();
        model.setViewName("/ceramics/transform");
        return model;
    }

    @RequestMapping("/ceramics")
    public ModelAndView ceramics() {
        ModelAndView model = new ModelAndView();
        model.setViewName("/ceramics/ceramics");
        return model;
    }

    @RequestMapping(value = "/download", method = RequestMethod.POST)
    public void downloadFile(HttpServletResponse response){
        try {
            String json = JedisClusterUtil.get(JxlExcelUtils.DATA_KEY);
            List<OrderTmplPo> result = JSONArray.parseArray(json, OrderTmplPo.class);
            if (CollectionUtils.isNotEmpty(result)){
                String title = "城配基础数据"+ DateUtil.format(DateUtil.DATE_TIME_1)+".xls";
                Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), OrderTmplPo.class, result);
                ExcelUtils.download(workbook, title, response);
                JedisClusterUtil.del(JxlExcelUtils.DATA_KEY);
            }
        }catch (Exception e){

        }
    }


    /**
     * 导入陶瓷原始单信息
     * @param response
     * @param request
     */
    @ApiOperation(value = "导入陶瓷原始单信息", notes = "导入陶瓷原始单信息")
    @RequestMapping(value = "/ceramics_load", method = RequestMethod.POST)
    public void loadExcel(HttpServletResponse response, MultipartHttpServletRequest request) {
        List<MultipartFile> files = request.getFiles("file");
        for (MultipartFile file : files) {
            System.out.println(file.getOriginalFilename());
        }
        MultipartFile baseFile = files.get(0);
        MultipartFile loadFile = files.get(1);
        ceramicsImportService.importLoadExcel(baseFile, loadFile, response);
    }

    @RequestMapping("/ceramics_index")
    public ModelAndView toCeramicsLoadform() {
        ModelAndView model = new ModelAndView();
        model.setViewName("/ceramics/load");
        return model;
    }

}
